using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Security;
using MyStack.Models;

namespace MyStack.Controllers
{
	public class StackController : Controller
	{
		//
		// GET: /Stack/

		//	By default, display the current user's stack
		public ActionResult Index()
		{
			string current_user = User.Identity.Name;

			//	Not logged on? take 'em to the logon page
			if (current_user == String.Empty)
			{				
				return RedirectToAction("LogOn", "Account");
			}
			//	Logged on? ok then, show 'em thier stack
			else
			{
				MyStackRepository db = new MyStackRepository();
				int id = db.GetUserIdByName(current_user);

				StackView stack = db.GetStackViewByUser(id);

				return View("Current", stack);
			}
		}

		/// <summary>
		/// Get the current stack of the specified user
		/// </summary>
		/// <param name="id">
		/// Id, optional, the id of the user's stack to display.  
		/// If null we will use the currently logged on user</param>
		/// <returns>View of the current stack</returns>
		public ActionResult Current(int? id)
		{
			MyStackRepository db = new MyStackRepository();

			string current_user = User.Identity.Name;

			//	If id is specified, use it,
			//	otherwise lookup the current user
			int current_user_id =
				id ?? db.GetUserIdByName(current_user);

			StackView stack = db.GetStackViewByUser(current_user_id);

			//	Show the current stack
			return View("Current", stack);
		}

        public ActionResult Activity(int id)
        {
            MyStackRepository db = new MyStackRepository();

            // check if the user exists
            try
            {
                db.GetUser(id);
            }
            catch
            {
                return View("index");
            }

            StoriesView[] stories = db.getUserActivity(id);
            return View("Activity", stories);
        } 

		/// <summary>
		/// Get the page to push a new story on the stack
		/// 
		/// This controller simply displays the push page
		/// for the user to input thier story details
		/// </summary>
		public ActionResult Push()
		{
			//	Not logged on? take 'em to the logon page
			if (User.Identity.Name == String.Empty)
			{
				return RedirectToAction("LogOn", "Account");
			}
			//	Logged on? ok then, show 'em thier stack
			else
			{
				MyStackRepository db = new MyStackRepository();

				Story newStory = new Story();

				return View(newStory);
			}
		}

		/// <summary>
		/// Push a new story onto the stack
		/// </summary>
		[AcceptVerbs(HttpVerbs.Post)]
		
		//	We have to disable input validation to allow
		//	the rich text input to pass the HTML to the
		//	server, the title / content required validation
		//	still works
		[ValidateInput(false)]
		public ActionResult Push(FormCollection formValues)
		{
			MyStackRepository db = new MyStackRepository();

			int userId = db.GetUserIdByName(User.Identity.Name);

			Story newStory = new Story();

			//	Here the framework automatically fills the object
			UpdateModel<Story>(newStory);
            if ( ValidatePush(newStory.Title, newStory.Content) )
            {
                db.Push(userId, newStory);

                //	Now display the updated stack
                return RedirectToAction("Current");
            }
            else
            {
                // Validation failed - redisplay form
                return View();
            }
		}

		public ActionResult Pop(int storyid)
		{
            string current_user = User.Identity.Name;
            if (current_user == String.Empty)
            {
                return RedirectToAction("LogOn", "Account");
            }

            MyStackRepository db = new MyStackRepository();

			int userId = db.GetUserIdByName(User.Identity.Name);

			

			Story story = db.GetStory(storyid);

			

			//	If the user doesn't have this story on thier stack
			//	pop it
			if (db.GetStoryOwner(storyid) != userId)
			{
				db.Pop(userId, storyid);
			}
			//	Otherwise we will just diplay the story

			//	Show the story
			return RedirectToAction("View", "Story", new { id = storyid });
		}

        private bool ValidatePush(string title, string content)
        {
            if (String.IsNullOrEmpty(title.Trim()))
            {
                ModelState.AddModelError("Title", "You must specify a title.");
            }
            else if (title.Length > 100)
            {
                ModelState.AddModelError("Title", "Title must be less than 100 characters!");
            }

            if (String.IsNullOrEmpty(content))
            {
                ModelState.AddModelError("Content", "You must specify content.");
            }
            return ModelState.IsValid;
        }
	}
}
